/**
 * @(#)YoudaoTranslateService.java, 2013-2-12. Copyright 2013 RENREN, Inc. All
 *                                  rights reserved. RENREN
 *                                  PROPRIETARY/CONFIDENTIAL. Use is subject to
 *                                  license terms.
 */
package com.wennimei.service;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wennimei.enums.MessageTypeEnum;
import com.wennimei.util.HttpUtil;

/**
 * @author shichen.feng@renren-inc.com
 */
@Service
public class YoudaoTranslateService {

    @SuppressWarnings("unchecked")
    public String get(String content) {
        content = content.replaceAll(
                MessageTypeEnum.TRANSLATE.getReplaceRegx(), "");
        String url = "http://fanyi.youdao.com/openapi.do?"
                + "keyfrom=wennimei&key=361379114&type=data&doctype=json&version=1.1&q="
                + content;
        String json = HttpUtil.get(url);
        Gson gson = new Gson();
        Map<String, Object> res = gson.fromJson(json,
                new TypeToken<Map<String, Object>>() {}.getType());
        Map<String, Object> map = (Map<String, Object>) res.get("basic");
        if(null == map)
            return "暂未查到该单词的意思，请查看拼写是否正确";
        List<String> explains = (List<String>) map.get("explains");
        StringBuilder sb = new StringBuilder();
        sb.append(content + "\r\n").append(map.get("phonetic") + "\r\n");
        for (String s: explains) {
            sb.append(s + "\r\n");
        }
        return sb.toString();
    }
}
